package com.central.scheduler.master.runner.task;

import com.central.common.enums.TaskType;
import com.central.scheduler.common.Constants;

import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Tindy
 * @date 2021/11/7
 * @describe
 * the factory to create task processor
 */
public class TaskProcessorFactory {

    public static final Map<String, ITaskProcessFactory> PROCESS_FACTORY_MAP = new ConcurrentHashMap<>();

    private static final String DEFAULT_PROCESSOR = Constants.COMMON_TASK_TYPE;

    static {
        for (ITaskProcessFactory iTaskProcessor : ServiceLoader.load(ITaskProcessFactory.class)) {
            PROCESS_FACTORY_MAP.put(iTaskProcessor.type(), iTaskProcessor);
        }
    }

    public static ITaskProcessor getTaskProcessor(TaskType type) {
        if (type==null) {
            return PROCESS_FACTORY_MAP.get(DEFAULT_PROCESSOR).create();
        }
        if (!PROCESS_FACTORY_MAP.containsKey(type.getDesc())) {
            return PROCESS_FACTORY_MAP.get(DEFAULT_PROCESSOR).create();
        }
        return PROCESS_FACTORY_MAP.get(type.getDesc()).create();
    }

}
